package com.reference;

import org.junit.rules.ExternalResource;

import javax.security.auth.Refreshable;
import java.lang.ref.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Author: tgy
 * @Date: 2020-08-04 11:08
 *
 *
 * -Xms5M -Xmx5M -XX:+PrintGCDetails
 */
public class ReferenceTest {
    /**
     *
     * Reference : 强引用
     * SoftReference ： 软引用 在内存不足是释放
     * WeakReference ： gc调用时释放
     * PhantomReference： 虚引用
     */
    public static void main(String[] args) {

        ReferenceQueue<Object> objectReferenceQueue = new ReferenceQueue<>();
        Object key = new Object();

        WeakReference<Object> objectWeakReference = new WeakReference<>(key, objectReferenceQueue);
        key = null;
//        System.out.println(objectReferenceQueue.poll());

        System.gc();

        try {

            Reference<?> remove = objectReferenceQueue.remove();
            System.out.println("11111111111" + remove);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

////        TimeUnit.SECONDS.sleep(2);
//        System.out.println(objectWeakReference.get());
//
//        System.out.println(objectReferenceQueue.poll());


//        weakHashMap();

//        weakReference();


//        softReference();

    }

    private static void weakHashMap() {
        Map<Object,Object> map = new WeakHashMap<>();

        Object key = new Object();
        map.put(key,new Object());



        key = null;
        System.out.println(map.size());

        System.gc();

        System.out.println(map.size());
    }

    private static void weakReference() {
        Object o = new Object();
        WeakReference<Object> objectWeakReference = new WeakReference<>(o);

        o = null;

        System.gc();

        System.out.println(objectWeakReference.get());
    }

    private static void softReference() {
        Object obj = new Object();


        SoftReference<Object> objectSoftReference = new SoftReference<>(obj);

        obj = null;

        System.gc();

        System.out.println("=============" + objectSoftReference.get());


//        List<byte []> list = new ArrayList<>();
//
//
//        try {
//
//            for (int i = 0; i < 10; i++) {
//
//                list.add(new byte[1024 * 1024 * 10]);
//            }
//
//        }catch (Throwable throwable){
//
//            System.out.println("--------------" + throwable.getMessage());
//        }finally {
//
//            System.out.println("=============" + objectSoftReference.get());
//        }

    }
}

